// tooltip.js
import { isNumber, isObject } from 'lodash-es'

export class Tooltip {
  labels = []
  values = []
  parentDom = null
  visible = false
  blockInfo = {}

  // 插槽dom
  slotDom = null
  // tooltip最外层dom及其位置
  $el = null
  position = new Proxy({ x: 0, y: 0 }, {
    get: function (obj, prop) {
      return prop in obj ? obj[prop] : undefined
    },
    set: (obj, prop, value) => {
      if (prop !== 'x' && prop !== 'y') {
        throw new TypeError(`${prop} is not valid property`)
        return false
      }
      if (!isNumber(value)) {
        throw new TypeError(`${value} is not a number`)
        return false
      }
      obj[prop] = value
      this.$el.style.cssText = `display: ${this.visible ? 'block' : 'none'}; position: absolute; left: ${obj.x}px; top: ${obj.y}px;`
      return true
    },
  })

  constructor(parent, formatter) {
    this.$el = document.createElement('div')
    // 允许自定义tooltip
    if (typeof formatter === 'function') {
      this.updateSlotDom = () => {
        this.$el.innerHTML = formatter(this.blockInfo)
      }
    } else {
      this.slotDom = this.defaultTooltip()
      this.updateSlotDom()
      this.$el.appendChild(this.slotDom)
    }
    this.parentDom = parent
    this.parentDom.appendChild(this.$el)
    this.$el.style.cssText = 'display: none;'
  }

  defaultTooltip() {
    const dom = document.createElement('div')
    dom.style.cssText = `
      background-color: white;
      padding: 10px 8px;
      border-radius: 6px;
      box-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.15);
    `
    return dom
  }

  // 刷新slotDom
  updateSlotDom() {
    const { color, title, value } = this.blockInfo
    console.log(this.blockInfo)
    this.slotDom.style.border = `2px solid ${color || 'black'}`
    this.slotDom.innerHTML = `
      <div style="font-size: 14px; white-space: nowrap;">
        ${title || '--'}:
        <span style="font-weight: bold; color: ${color};">${value || '--'}</span>
      </div>
    `
  }

  show() {
    this.$el.style.cssText = this.$el.style.cssText.replace('display: none', 'display: block')
  }

  hide () {
    this.$el.style.cssText = this.$el.style.cssText.replace('display: block', 'display: none')
  }
}
